<template>
  <common-view class="third-page">
    <design-view>
      <img src="../assets/img/pick_title.png" class="title" alt=""/>
      <van-form
        class="form"
        :show-error-message="false"
        :show-error="false"
        validate-trigger="onSubmit"
        validate-first
        @submit="onSubmit"
        @failed="onFailed">
        <div class="form-container">
          <div class="field-container brand-field-container">
            <van-field
              v-model.trim="showBrandText"
              name="brand"
              center
              :rules="rules.brand"
              disabled class="field-brand field"
              placeholder="请选择品牌">
              <template #button>
                <van-icon name="arrow-down"/>
              </template>
            </van-field>
            <div class="btn-cover"  @click="onOpenDropMenu"></div>
            <!-- 下滑进入 -->
            <transition name="van-fade">
              <div v-show="visible" class="field-drop-menu">
                <van-cell-group>
                  <van-cell size="small" value="和成天下"  @click="onSelectBrand(0)">
                    <template #right-icon>
                      <van-icon v-if="brand === 0" name="success" />
                    </template>
                  </van-cell>
                  <van-cell size="small" value="口味王"  @click="onSelectBrand(1)">
                    <template #right-icon>
                      <van-icon v-if="brand === 1" name="success" />
                    </template>
                  </van-cell>
                </van-cell-group>
              </div>
            </transition>
          </div>
          <div class="field-container nickname-field-container">
            <van-field
              v-model.trim="nickname"
              name="nickname"
              maxlength="10"
              center
              :rules="rules.nickname"
              class="field-nickname field"
              placeholder="请输入昵称"/>
          </div>
          <div class="field-container field-upload-container">
            <div class="upload-btn">
              <upload-file @onCrop="onCrop"></upload-file>
            </div>
            <img v-if="uploadedFile" :src="uploadedFile.url" alt="" class="preview-image"/>
          </div>
          <div class="field-container desc-field-container">
            <van-field
              v-model.trim="content"
              name="desc"
              center
              type="textarea"
              class="field field-desc"
              maxlength="300"
              show-word-limit
              :rules="rules.content"
              placeholder="在此输入爱的故事内容，故事需与品牌“口味王”或“和成天下”520狂欢节相关，限300字内，详见活动规则。"/>
          </div>
        </div>
        <van-button class="btn" native-type="submit">点击提交</van-button>
      </van-form>
    </design-view>
  </common-view>
</template>
<script>
import {
  Field, DropdownMenu,
  DropdownItem,
  Icon, Cell, CellGroup, Toast,
  Form, Button,
  Dialog
} from 'vant'

import UploadFile from '@/components/UploadComponent'
import { API_HOST } from '@/common/config'
import { UPDATE_PICK_WORKS } from '@/store/mutation-types'
import { uploadUserStory } from '@/common/api'
export default {
  name: 'ThirdView',
  components: {
    UploadFile,
    [Field.name]: Field,
    [DropdownMenu.name]: DropdownMenu,
    [DropdownItem.name]: DropdownItem,
    [Icon.name]: Icon,
    [CellGroup.name]: CellGroup,
    [Cell.name]: Cell,
    [Form.name]: Form,
    [Button.name]: Button
  },
  data () {
    return {
      brand: -1,
      nickname: '',
      content: '',
      visible: false,
      // 上传的文件
      uploadedFile: null,

      // 上传cos的地址
      uploadedFileCosUrl: '',
      // 验证规则
      rules: {
        brand: [{
          required: true,
          message: '请选择品牌'
        }],
        nickname: [{
          required: true,
          message: '请输入昵称'
        }],
        picture: [{
          required: true,
          message: '请上传图片'
        }],
        content: [{
          required: true,
          message: '请输入故事内容'
        }]
      }
    }
  },
  computed: {
    showBrandText () {
      if (this.brand < 0) return ''
      // 0和成天下 1=口味王
      return ['和成天下', '口味王'][this.brand]
    }
  },
  mounted () {
    this.initCos()
  },
  methods: {
    onOpenDropMenu () {
      this.visible = !this.visible
      this.$sound && this.$sound.play()
    },
    onSelectBrand (brand) {
      this.brand = brand
      this.visible = false
      this.$sound && this.$sound.play()
    },
    initCos () {
      // eslint-disable-next-line no-undef
      this.cos = new TencetCloudUploadFile({
        Bucket: 'youlan-1251454229',
        path: '20240423/',
        authUrl: API_HOST + '/uploadcos/v1/upload/index'
      })
      return this.cos
    },
    // 上传文件到cos
    putObject (fileObj) {
      return new Promise((resolve, reject) => {
        this.cos.putObject(fileObj.file, (err, res) => {
          if (err) {
            reject(err)
          } else {
            resolve(res)
          }
        })
      })
    },
    onCrop (file) {
      console.log(file)
      if (file) {
        this.uploadedFile = file
      } else {
        Toast('读取图片失败')
      }
    },
    // 校验失败
    onFailed ({ errors }) {
      this.$sound && this.$sound.play()
      if (!errors.length) {
        return
      }
      const [{ message }] = errors
      Dialog.alert({
        message
      })
    },
    // 使用cdn地址
    getThumb (location) {
      const url = location.replace('youlan-1251454229.cos.ap-shanghai.myqcloud.com', 'youlan-1251454229.file.myqcloud.com')
      return `https://${url}`
    },
    // 提交数据
    async onSubmit (values) {
      this.$sound && this.$sound.play()
      if (!this.uploadedFile) {
        Dialog.alert({ message: '请上传图片' })
        return
      }
      const loading = Toast.loading({
        message: 'Loading...',
        forbidClick: true,
        duration: 0
      })
      try {
        this.uploadedFileCosUrl = await this.putObject(this.uploadedFile)
        if (!this.uploadedFileCosUrl || !this.uploadedFileCosUrl.Location) {
          throw new Error()
        }
        const photo = this.getThumb(this.uploadedFileCosUrl.Location)
        const userStory = {
          nickname: this.nickname,
          brand: this.brand,
          content: this.content,
          photo
        }
        const { status, message } = await uploadUserStory(userStory) || {}
        if (status <= 0) {
          Dialog.alert({ message })
          return
        }
        this.$store.commit(UPDATE_PICK_WORKS, userStory)
        await this.$createPoster()
        this.$emit('next-page')
      } catch (e) {
        console.error(e)
      } finally {
        loading.clear()
      }
    }
  }
}
</script>
<style scoped lang="scss">
@import "../assets/css/mixin.scss";
input {
  background-color: transparent;
}
.third-page {
  background: url(../assets/img/second/bg.jpg) center no-repeat; // modify
  background-size: 100% 100%;
}
.title {
  @include wh(492, 135);
  margin:  99px auto 20px;
  display: block
}
.form-container {
  @include wh(637, 817);
  border-radius: 28px;
  overflow: hidden;
  margin:  0 auto;
  padding: 52px 46px 59px 50px;
  background: {
    image: url(../assets/img/customisized_bg.png);
    position: center;
    repeat: no-repeat;
    size: 100% 100%;
  }
}

.field, .field:disabled {
  background: transparent;
  ::v-deep(input) {
    font-size: 24px;
    background: transparent;
    color: red;
    text-align: left;
    border: none;
    -webkit-text-fill-color: red;
  }
  &:disabled {
    -webkit-text-fill-color: red;
  }
  &.field-brand,
  &.field-nickname {
    height: 66px;
    ::placeholder {
      color: red;
      -webkit-text-fill-color: red;
    }
  }
  &.field-desc {
    height: 230px;
  }
}
.field-container {
  border-radius: 10px;
  border: 2px solid #ca0a0a;
  background: transparent;
  position: relative;
  width: 100%;
  height: 66px;
  .btn-cover {
    position: absolute;
    left:0;
    right:0;
    bottom: 0;
    top: 0;
  }
  &.nickname-field-container {
    margin: 32px auto 36px;
  }
  &.desc-field-container {
    margin: 46px auto 0 ;
  }
  &.desc-field-container {
    height: 227px;
    font-size: 24px;
    line-height: 1.2;
    ::placeholder {
      font-size: 20px;
      line-height: 1.2;
    }
  }
}
.field-upload-container {
  width: 100%;
  height: 224px;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  background: url(../assets/img/upload_bg.png) center 53px no-repeat;
  background-size: 237px 139px;
  .upload-btn {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    height: 100%;
    overflow: hidden;
  }
  .preview-image {
    width: 100%;
    height: 100%;
  }
}
.field-drop-menu {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background-color: red;
  color: #fff;
  z-index: 1000;
  ::v-deep {
    .van-cell-group,
    .van-cell__value,
    .van-cell {
      background-color: transparent;
      color: #fff
    }
  }
}
.uploaded {
  width: 100%;
  height: 100%;
}
.btn {
  @include wh(479,88);
  background: url(../assets/img/second/btn_bg.png) center no-repeat;
  background-size: 100% 100%;
  border: none;
  margin: 47px auto 0;
  color: #fff;
  display: block;
  font-size: 40px;
}
</style>
